﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using Zzj.Model;
using Zzj.Utils;

namespace Zzj.Windows
{
    /// <summary>
    /// HttpPostWindow.xaml 的交互逻辑
    /// </summary>
    public partial class HttpPostWindow : Window
    {
        private SynchronizationContext _syncContext = null;
        private String message = null;
        private JObject resultObject = null;
        private JArray resultArray = null;
        private JObject paramObject = null;

        private string warning = null;
        private string operation = "0";

        public enum OperationType
        {
            getBillByCard,
            uploadMakeCardResult,
            getBillByCardGuidForAccount,
            billAccount,
            getBillByID,
            getBillsByCardForPrint,
            queryBillPrintCount,
            doReport
        }

        public HttpPostWindow()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            this.Loaded += Winndow_Loaded;
        }

        public void setOperation(string _val)
        {
            this.operation = _val;
        }

        public String getWarning()
        {
            return warning;
        }

        public String getMessage()
        {
            return message;
        }

        public JObject getResultObject()
        {
            return resultObject;
        }

        public JArray getResultArray()
        {
            return resultArray;
        }

        public void setParamObject(JObject param)
        {
            this.paramObject = param;
        }

        private void Winndow_Loaded(object sender, RoutedEventArgs e)
        {
            if (OperationType.getBillByCard.ToString().Equals(operation))
            {
                getBillByCard();
            }
            else if (OperationType.uploadMakeCardResult.ToString().Equals(operation))
            {
                uploadMakeCardResult();
            }
            else if (OperationType.getBillByCardGuidForAccount.ToString().Equals(operation))
            {
                getBillByCardGuidForAccount();
            }
            else if (OperationType.billAccount.ToString().Equals(operation))
            {
                doBillAccount();
            }
            else if (OperationType.getBillByID.ToString().Equals(operation))
            {
                getBillByID();
            }
            else if (OperationType.getBillsByCardForPrint.ToString().Equals(operation))
            {
                getBillsByCardForPrint();
            }
            else if (OperationType.queryBillPrintCount.ToString().Equals(operation))
            {
                getBillPrintCount();
            }
            else if (OperationType.doReport.ToString().Equals(operation))
            {
                doReport();
            }
        }

        private void doReport()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/makeCard/report", paramJSON.ToString());
                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        _syncContext.Post(CloseWindow, getResultObj("success"));
                    }
                    else
                    {
                        _syncContext.Post(CloseWindow, getResultObj("error"));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员";
                    Thread.Sleep(1000);
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void getBillByCard()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/makeCard/getBillInfoNew", paramJSON.ToString());

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    JObject newJson = new JObject();
                    if (status.ToLower() == "00000")
                    {
                        var jsonStr = respJson["data"].ToString();
                        List<BillModel> bills = JsonConvert.DeserializeObject<List<BillModel>>(jsonStr);

                        Thread.Sleep(1000);
                        if (null == bills || bills.Count == 0)
                        {
                            _syncContext.Post(CloseWindow, getResultObj("error"));
                        }
                        else
                        {
                            _syncContext.Post(CloseWindow, getResultArray("success", JArray.FromObject(bills)));
                        }
                    }
                    else
                    {
                        _syncContext.Post(CloseWindow, getResultObj("error"));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员";
                    Thread.Sleep(1000);
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void getBillByCardGuidForAccount()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/makeCard/getBillInfoNew", paramJSON.ToString());
                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        var jsonStr = respJson["data"].ToString();
                        List<BillModel> bills = JsonConvert.DeserializeObject<List<BillModel>>(jsonStr);

                        Thread.Sleep(1000);
                        if (null == bills || bills.Count == 0)
                        {
                            _syncContext.Post(CloseWindow, getResultObj("error"));
                        }
                        else if (bills.Count > 1)
                        {
                            _syncContext.Post(CloseWindow, getResultObj("error"));
                        }
                        else
                        {
                            _syncContext.Post(CloseWindow, getResultObj("success", JObject.FromObject(bills[0])));
                        }
                    }
                    else
                    {
                        _syncContext.Post(CloseWindow, getResultObj("error"));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员";
                    Thread.Sleep(1000);
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void uploadMakeCardResult()
        {
            new Thread(() =>
            {
                String msg = "";
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/makeCard/uploadBillMakeCardResult", paramJSON.ToString());

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        JObject jsonStr = (JObject)respJson["data"];
                        string code = jsonStr.GetValue("code").ToString();
                        msg = jsonStr.GetValue("msg").ToString();
                        if ("200".Equals(code))
                        {
                            _syncContext.Post(CloseWindow, getResultObj("success"));
                        }
                        else
                        {
                            JObject jobj = new JObject();
                            jobj.Add("Message", msg);
                            _syncContext.Post(CloseWindow, getResultObj("error", jobj));
                        }
                    }
                    else
                    {
                        msg = (string)respJson["message"];
                        JObject jobj = new JObject();
                        jobj.Add("Message", msg);
                        _syncContext.Post(CloseWindow, getResultObj("error", jobj));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员";
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void doBillAccount()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/settlementByFac", paramJSON.ToString());

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        _syncContext.Post(CloseWindow, getResultObj("success"));
                    }
                    else
                    {
                        JObject msgObj = new JObject();
                        msgObj.Add("Message", respJson["msg"].ToString());
                        _syncContext.Post(CloseWindow, getResultObj("success", msgObj));
                    }
                }
                catch (Exception ex)
                {
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void getBillByID()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/clientApi/queryBillDetail", paramJSON.ToString());

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        var jsonStr = respJson["data"].ToString();
                        BillModel bill = JsonConvert.DeserializeObject<BillModel>(jsonStr);

                        Thread.Sleep(1000);

                        _syncContext.Post(CloseWindow, getResultObj("success", JObject.FromObject(bill)));
                    }
                    else
                    {
                        _syncContext.Post(CloseWindow, getResultObj("error"));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员" + ex.ToString();
                    Thread.Sleep(1000);
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void getBillsByCardForPrint()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/makeCard/getBillPrintInfo", paramJSON.ToString());

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        var jsonStr = respJson["data"].ToString();
                        List<BillModel> bills = JsonConvert.DeserializeObject<List<BillModel>>(jsonStr);

                        Thread.Sleep(1000);
                        if (null == bills || bills.Count == 0)
                        {
                            _syncContext.Post(CloseWindow, getResultObj("error"));
                        }
                        else
                        {
                            _syncContext.Post(CloseWindow, getResultArray("success", JArray.FromObject(bills)));
                        }
                    }
                    else
                    {
                        _syncContext.Post(CloseWindow, getResultObj("error"));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员";
                    Thread.Sleep(1000);
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private void getBillPrintCount()
        {
            new Thread(() =>
            {
                try
                {
                    JObject paramJSON = JObject.Parse(paramObject.ToString());
                    String response = HttpPostHelper.doHttpPost("/qd-s-factory/clientApi/queryBillSelfPrint", paramJSON.ToString());

                    JObject respJson = JObject.Parse(response);
                    string status = respJson["code"].ToString();
                    if (status.ToLower() == "00000")
                    {
                        var count = respJson["data"].ToString();

                        Thread.Sleep(1000);
                        if (null == count)
                        {
                            _syncContext.Post(CloseWindow, getResultObj("error"));
                        }
                        else
                        {
                            JObject result = new JObject();
                            result.Add("count", count);
                            _syncContext.Post(CloseWindow, getResultObj("success", JObject.FromObject(result)));
                        }
                    }
                    else
                    {
                        _syncContext.Post(CloseWindow, getResultObj("error"));
                    }
                }
                catch (Exception ex)
                {
                    message = "系统异常,请联系管理员";
                    Thread.Sleep(1000);
                    _syncContext.Post(CloseWindow, getResultObj("error"));
                }
            }).Start();
        }

        private JObject getResultObj(String result, JObject resultObject = null)
        {
            JObject messageObject = new JObject();
            messageObject.Add("result", result);
            if (null != resultObject)
            {
                messageObject.Add("object", resultObject);
            }
            return messageObject;
        }

        private JObject getResultArray(String result, JArray resultObject = null)
        {
            JObject messageObject = new JObject();
            messageObject.Add("result", result);
            if (null != resultObject)
            {
                messageObject.Add("array", resultObject);
            }
            return messageObject;
        }

        private void CloseWindow(object respObj)
        {
            JObject respObject = (JObject)respObj;

            String status = (String)respObject.GetValue("result");
            if ("success".Equals(status))
            {
                this.DialogResult = true;
                if (respObject.ContainsKey("object"))
                {
                    if (null != respObject.GetValue("object"))
                    {
                        this.resultObject = (JObject)respObject.GetValue("object");
                    }
                }
                if (respObject.ContainsKey("array"))
                {
                    if (null != respObject.GetValue("array"))
                    {
                        this.resultArray = (JArray)respObject.GetValue("array");
                    }
                }
            }
            else
            {
                this.DialogResult = false;
                if (respObject.ContainsKey("object"))
                {
                    if (null != respObject.GetValue("object"))
                    {
                        this.resultObject = (JObject)respObject.GetValue("object");
                        String msg = (String)this.resultObject.GetValue("Message");
                        message = msg;
                    }
                }
                if (respObject.ContainsKey("array"))
                {
                    if (null != respObject.GetValue("array"))
                    {
                        this.resultArray = (JArray)respObject.GetValue("array");
                    }
                }
            }

            this.Close();
        }
    }
}